package com.company.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.common.JwtUtils;
import com.company.common.R;
import com.company.entity.User;
import com.company.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@RestController
public class UserController {
    @Resource
    UserService userService;

    /*
     * 管理员登录
     * */
    @CrossOrigin(origins = "*")
    @PostMapping("/LoginUser")
    public R Login(@RequestBody User user){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.setEntity(user);
        User one = this.userService.getOne(queryWrapper);
        if (one == null){
            return new R().setCode(502).setMessage("用户名密码错误");
        }else{
            HashMap<String,Object> hashMap=new HashMap<>();
            hashMap.put("id",one.getId());
            hashMap.put("name",one.getName());
            hashMap.put("password",one.getPassword());
            String jwtToken= JwtUtils.createJwtToken(hashMap);
            return new R().add("jwtToken",jwtToken);
        }
    }

    /*
    * 查询所有
    * */
    @CrossOrigin(origins = "*")
    @RequestMapping("/selectAllUser")
    public R selectAllUser(){
        List<User> list = this.userService.list();
        return new R().add("list",list);
    }

    @CrossOrigin(origins = "*")
    @RequestMapping("/selectAllUserid/{id}")
    public R selectAllUserid(@PathVariable("id") int id){
        User byId = this.userService.getById(id);
        return new R().add("byId",byId);
    }
    @CrossOrigin(origins = "*")
    @PostMapping("/updateUser")
    public R updateUser(@RequestBody User user){
        this.userService.updateById(user);
        return new R();
    }
}
